import Request from 'luch-request'
import { BASE_URL, WHITELIST } from './constant'
import { useUserStore } from '@/store/user'



// 1. 创建Request实例对象
const request = new Request({
  // 接口基地址
  baseURL:BASE_URL,
  custom: {
    loading: true
  }
})

// 3. 配置请求拦截器
request.interceptors.request.use(
  (config) => {
    if(config.custom?.loading === true){
      uni.showLoading({ title: '正在加载...', mask: true })
    }
    const store = useUserStore()
    if (store.token && !WHITELIST.includes(config.url!)) {
     config.header!.Authorization = `Bearer ${store.token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 4. 配置响应拦截器
request.interceptors.response.use(
  (res) => {
    // 关闭弹层
    uni.hideLoading()
    if (res.data.code !== 10000) {
      uni.showToast({
        title: res.data.message,
        icon: 'none',
      })
      return Promise.reject(res.data)
    }
    return res.data?.data
  },
  (error) => {
    // 关闭弹层
    uni.hideLoading()
    uni.showToast({
      title: error.data.message,
      icon: 'none',
    })
    if(error.statusCode === 401){
      //  跳转到登录页面
      uni.reLaunch({
        url:'/pages/login/index'
      })
    }
    return Promise.reject(error)
  }
)


// 2. 导出
export { request }